import cfg from '../../config';
import {getView} from '../../util/api';
import {formatDate, getCurrDay, randomColor, isArrContain, isArrNoContain, findStr, backPage, getPrevDate, getNextDate, message, closeMsg, removeCls} from '../../util/aid';
import * as ajax  from '../../lib/kajax';
import * as pullFresh from '../../lib/kpullFresh';
import {getSeatParam}  from '../common';
import Dialog  from '../../lib/kdialog';
const dialog = new Dialog();

const $ = require('../../lib/kdom');
let _view = require('raw-loader!./list.html');

let currQuantity = 0;//当前加载的list条数
let _opts = null;//父页面的参数
let listDataArr = null;
let keysort = '0'; // 0顺序，1倒序

export default class {
    path = '/train/list$';
    hash = '/train/list';
    title = '火车票';

    constructor(opt) {
        opt = opt || {};
        this.path = opt.path || this.path;
        this.hash = opt.hash || this.hash;
        this.title = opt.title || this.title;
    }

    // 输出视图
    view(cb) {
        if (!_view) {
            // 静态资源浏览器有缓存,增加时标,强制刷新!
            getView(`${cfg.train.view.list}?t=${(+new Date())}`, '', (rs) => {
                _view = rs;
                cb(null, _view);
            });
        } else
            cb(null, _view);
    }

    // 在已经加载的视图上操作
    bind(dv, params) {
        console.log('我是列表页：', params);
        // 加载动画
        dialog.loading();
        _opts = params.opts;
        // _opts = params.opts || {"date": "2017-07-16", "from": "CQW,重庆", "highMotor": false, "to": "BJP,北京", "url": "/train/home"};
        let msg = '';
        let tabItem = $.qus('#navShadow>.tab-item');

        const refreshBox = $.qu('.pull-to-refresh-content');//下拉刷新页面的盒子

        // 初始化下拉刷新页面
        pullFresh.start(refreshBox);

        // 添加'refresh'监听器
        $(refreshBox).on('refresh', (e) => {
            // 模拟1s的加载过程
            setTimeout(() => {
                dialog.loading();
                listDataFun(_opts);
                removeCls($.qus('#navShadow>.tab-item'), 'active', () => {
                    $.html($.qu('#filterSTime>.tab-label'), '出发');
                    $.html($.qu('#filterLongTime>.tab-label'), '时长');
                    $.html($.qu('#filterPrice>.tab-label'), '价格');
                });

                pullFresh.done('.pull-to-refresh-content');
            }, 1000);
        });


        // 初始化
        setTrianDate(_opts.date);
        if (_opts.from) $.html(listTitelAdder, `${_opts.from.split(',')[1]}-${_opts.to.split(',')[1]}`);

        // 加载数据
        listDataFun(_opts);

        //条件查询
        // 上一天
        prevDate.onclick = (e) => {
            if ($.hasClass(prevDate, 'active')) return;
            dialog.loading();
            setTrianDate(prevDate.getAttribute('data-date'));
            _opts.date = todayDate.value;
            listDataFun(_opts);
        };

        // 当天
        todayDate.onchange = (e) => {
            dialog.loading();
            setTrianDate(todayDate.value);
            _opts.date = todayDate.value;
            listDataFun(_opts);
        };

        // 下一天
        nextDate.onclick = (e) => {
            dialog.loading();
            setTrianDate(nextDate.getAttribute('data-date'));
            _opts.date = todayDate.value;
            listDataFun(_opts);
        };

        // 开始时间筛选 // 第一次倒叙排列
        filterSTime.onclick = () => {
            if (keysort === '0') {
                keysort = '1';
                msg = '出发[从晚到早]'
            } else {
                keysort = '0';
                msg = '出发[从早到晚]'
            }
            handleSort(listDataArr, 'StartTime', keysort);
            removeCls(tabItem, 'active', () => {
                $.addClass(filterSTime, 'active');
                $.html($.qu('#filterSTime>.tab-label'), msg);
                $.html($.qu('#filterLongTime>.tab-label'), '时长');
                $.html($.qu('#filterPrice>.tab-label'), '价格');
            });
        };

        // 时长筛选
        filterLongTime.onclick = (e) => {
            if (keysort === '0') {
                keysort = '1';
                msg = '耗时[从慢到快]'
            } else {
                keysort = '0';
                msg = '耗时[从快到慢]'
            }
            handleSort(listDataArr, 'CostTime', keysort);
            removeCls(tabItem, 'active', () => {
                $.addClass(filterLongTime, 'active');
                $.html($.qu('#filterSTime>.tab-label'), '出发');
                $.html($.qu('#filterLongTime>.tab-label'), msg);
                $.html($.qu('#filterPrice>.tab-label'), '价格');
            });
        };

        // 价格筛选
        filterPrice.onclick = (e) => {
            if (keysort === '0') {
                keysort = '1';
                msg = '价格[从高到低]'
            } else {
                keysort = '0';
                msg = '价格[从低到高]'
            }
            handleSort(listDataArr, 'LowerPrice', keysort);
            removeCls(tabItem, 'active', () => {
                $.addClass(filterPrice, 'active');
                $.html($.qu('#filterSTime>.tab-label'), '出发');
                $.html($.qu('#filterLongTime>.tab-label'), '时长');
                $.html($.qu('#filterPrice>.tab-label'), msg);
            });
        };

        // backPage
        backPage('#pg-train-list', 'backPage', () => {
            if (_opts.keyword) {
                dialog.confirm({content: '您好！确定要放弃火车票改签吗？'}, (rs) => {
                    if (rs) {
                        $.router.go('/train/home', '', true);
                    }
                });
            } else
                $.router.go('/train/home', {opts: _opts}, true);
        });
    }

    /*bind*/
}

// 设置时间
function setTrianDate(val) {
    val = val ? val : new Date();
    if (new Date(val) > new Date()) {
        $.removeClass($.id('prevDate'), 'active');
    } else {
        $.addClass($.id('prevDate'), 'active');
    }
    $.id('prevDate').setAttribute('data-date', getPrevDate(val));
    $.id('todayDate').value = formatDate('yyyy-MM-dd', val);
    $.id('nextDate').setAttribute('data-date', getNextDate(val));
}

// 获取列表的数据，并做全局储存
function listDataFun(opt) {
    // console.log('data', data);
    if (!opt) return;
    let date = opt.date;
    if (opt.from && opt.to) {
        let from = opt.from.split(',');
        let to = opt.to.split(',');

        let param = `&date=${date}&fromcity=${from[0]}&tocity=${to[0]}`;
        // console.log(`${cfg.train.host}${cfg.train.gettrainlist}${param}`);
        ajax.get(`${cfg.train.host}${cfg.train.getAct}${cfg.train.gettrainlist}${param}`, '', (rs) => {
            if (rs) {
                let r = JSON.parse(rs);
                // console.log(r);
                if (r && r.data) {
                    r = r.data;
                    listDataArr = r;
                    // console.log('我是列表listDataArr', listDataArr);
                    createTrainListFun(r, opt);
                } else {
                    message('#trainListBox', '亲！您暂时还没有获取到车次的相关信息哦，请重新查询哦！');
                    dialog.close();
                }
            }
        });
    }
}

// 渲染列表
// @param data (list data)
function createTrainListFun(data) {
    if (!data) return;
    let LoadQuantity = parseInt(cfg.train.LoadQuantity);
    let contentBox = trainListBox;
    let len = currQuantity + LoadQuantity;// 获得加载的长度
    const lis = [];
    let obj = null;// 循环当前的JSON
    let rs = null;//所有的席别
    let price = 0; // 价格
    let seat = []; // 席位
    if (currQuantity <= 0) { // currQuantity 当前记录为0，清空盒子
        $.html(contentBox, '');
    }
    for (let i = currQuantity; i < len; i++) {
        seat = [];
        if (i + 1 == len) { // 等于当前长度，则退出循环
            currQuantity = len;
            break;
        }
        if (i >= data.length) {
            break;
        }
        obj = data[i];
        // 所有的席别
        let rs = getSeatParam(obj);
        // console.log(JSON.stringify(rs));
        if (rs.length > 0) {
            for (let j = 0; j < rs.length; j++) {
                if (j === 0) price = rs[j].price;
                seat.push(`<div><span class="text-disabled">${rs[j].seat}：</span>${rs[j].yuPiao === '-1' ? 0 : rs[j].yuPiao}张</div>`);
            }
            closeMsg('#trainListBox');
        } else {
            message('#trainListBox', '亲！您查询日期的车次都没有票了哦，请换查询日期哦！');
            continue;
        }
        const li = document.createElement('li');
        li.className = 'card';
        li.setAttribute('onclick', `showTrianListDel(${i})`);
        li.innerHTML = `<div class="card-content">
                          <div class="card-content-inner">
                              <div class="from">${obj.StartCity}</div>
                              <h3 class="text-danger">${obj.StartTime}</h3>
                          </div>
                          <div class="card-content-inner f06">
                              <div>${obj.TrainCode}</div>
                              <div class="address-list-split"></div>
                              <div class="text-disabled">${obj.CostTime}</div>
                          </div>
                          <div class="card-content-inner">
                              <div class="to">${obj.EndCity}</div>
                              <h3 class="to-time">${obj.EndTime} ${obj.OverNight}</h3>
                          </div>
                          <div class="card-content-inner">
                              <span class="text-danger f09"><span class="f06">￥</span>${price}</span>
                              <span class="text-disabled f06">起</span>
                          </div>
                      </div>
                      <div class="card-footer f06">
                        ${seat.join('')}
                      </div>`;
        lis.push(li);
    }
    /*i*/

    if (lis && lis.length > 0) {
        closeMsg('#trainListBox');
        const nd = $.childTag(contentBox, 'div');
        lis.forEach(dv => contentBox.insertBefore(dv, nd));
    } else {
        message('#trainListBox', '亲！您查询日期的车次都没有票了哦，请换查询日期哦！');
    }
    // 关闭加载动画
    dialog.close();
}

// 添加一个最低价的属性
function addLowerPriceAttr(data) {
    if (!data) return;
    let rs = null;
    let rc = data;
    for (let i = 0, len = rc.length; i < len; i++) {
        rs = getSeatParam(rc[i]);
        if (rs[0]) {
            rc[i].LowerPrice = rs[0].price;
        }
    }
    return rc;
}

// 根据关键字排序
// @param data // 数据
// @param attr // 属性值
// @param keysort // 0顺序，1倒序
function handleSort(data, attr, keysort) {
    dialog.loading();
    let rc = null;
    if (attr === 'LowerPrice') {
        data = addLowerPriceAttr(data);
    }
    if (keysort === '0') {
        rc = data.sort((x, y) => {
            return x[attr] > y[attr] ? 1 : -1;
        });
    } else {
        rc = data.sort((x, y) => {
            return x[attr] > y[attr] ? -1 : 1;
        });
    }
    createTrainListFun(rc);
}

window.showTrianListDel = (idx) => {
    $.router.go('/train/book', {data: listDataArr[idx], opts: _opts}, true);
};